﻿using System;
using System.Data;
using System.Data.Odbc;

using BizElements.Core.ProviderComponents;

namespace BizElements.Core.Odbc
{
    /// <summary>Builds <see cref="System.Data.Odbc.OdbcCommand"/> objects.</summary>
    sealed class OdbcCommandBuilder : IDbCommandBuilder
    {
        private static readonly IParameterRenderer parameterRenderer = new GenericParameterRenderer();

        public IDbCommand BuildCommand(string cmdText, DbParameterCollection parameters, CommandType cmdType)
        {
            IDbCommand cmd = new OdbcCommand();
            cmd.CommandText = cmdText;
            cmd.CommandType = cmdType;
            if (Settings.DefaultCommandTimeout != null)
                cmd.CommandTimeout = Settings.DefaultCommandTimeout.Value;

            foreach (DbParameter par in parameters)
                cmd.Parameters.Add(ConvertToNativeParameter(par));

            return cmd;
        }

        private static IDbDataParameter ConvertToNativeParameter(DbParameter dbParameter)
        {
            IDbDataParameter clone = new OdbcParameter();
            ((OdbcParameter)clone).IsNullable = dbParameter.IsNullable;
            clone.ParameterName = parameterRenderer.RenderParameterName(dbParameter);

            clone.DbType = dbParameter.DbType;
            clone.Direction = dbParameter.Direction;
            clone.Precision = dbParameter.Precision;
            clone.Scale = dbParameter.Scale;
            clone.Size = dbParameter.Size;
            clone.SourceColumn = dbParameter.SourceColumn;
            clone.SourceVersion = dbParameter.SourceVersion;
            clone.Value = dbParameter.Value;

            return clone;
        }
    }
}